package fxsjdcxt;

import java.awt.AWTEvent;
import java.awt.BorderLayout;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.sql.Connection;
import java.util.List;

import javax.sql.rowset.CachedRowSet;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JToolBar;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ColumnListHandler;

@SuppressWarnings("serial")
public class MainFrame extends JFrame {
	private static final String ACCESS_QRLIST_SELECT = "select SeqNo,AgName,format(AnaDate,'yyyy-mm-dd') & ' ' & format(AnaTime,'hh:nn:ss') as AnaDateTime,Kind,Num from QRList where SeqNo>%d and Mark='' order by SeqNo desc";
	private static final String ACCESS_QRDATA_SELECT = "select SeqNo,SubNo,DispEle,Content from QRData where SeqNo>%d and RevMark=0";
	private static final String SQLSERVER_QRLIST_SELECT = "select max(cast(id_ as int)) from t_fxsj";
	private static final String SQLSERVER_QRLIST_INSERT = "insert into t_fxsj (id_,xh_,fxz_,fxsj_,fxfs_,fxlx_,cdbj_) values (?,?,?,?,?,?,?)";
	private static final String SQLSERVER_QRDATA_INSERT = "insert into t_fxsj_mx (id_,xh_,ysmc_,ysnr_) values (?,?,?,?)";
	private static final String SQLSERVER_QRGROUP_INSERT = "insert into t_fxsj_fz (id_,gid_) values (?,?)";
	private static int count = 0;
	private static final String MSG_DC = "导出成功，共%d组数据";
	private static final String APP_TITLE = "分析数据导出系统";
	private ImageIcon image = new ImageIcon(MainFrame.class.getResource("app.png"));
	private ImageIcon image1 = new ImageIcon(MainFrame.class.getResource("exit.png"));
	private ImageIcon image2 = new ImageIcon(MainFrame.class.getResource("export.png"));
	private JToolBar toolBar = new JToolBar();
	private JButton button1 = new JButton("退出", image1);
	private JButton button2 = new JButton("导出", image2);
	private JLabel label = new JLabel(APP_TITLE);

	public MainFrame() {
		button1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int option = JOptionPane.showConfirmDialog(null, "确定退出系统", "系统提示", JOptionPane.YES_NO_OPTION);
				if (option == JOptionPane.YES_OPTION) {
					MainFrame.this.setVisible(false);
					MainFrame.this.dispose();
					System.exit(0);
				}
			}
		});
		button2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				button2.setEnabled(false);
				dc();
				button2.setEnabled(true);
			}
		});
		Toolkit toolkit = Toolkit.getDefaultToolkit();
		toolkit.addAWTEventListener(new AWTEventListener() {
			public void eventDispatched(AWTEvent event) {
				if (event.getClass() == KeyEvent.class) {
					KeyEvent ke = ((KeyEvent) event);
					if (ke.getKeyCode() == KeyEvent.VK_K && ke.isControlDown() && ke.isShiftDown() && ke.getID() == KeyEvent.KEY_PRESSED) {
						String data = JOptionPane.showInputDialog(null, "请输入要加密的字符串");
						if (data != null) {
							JOptionPane.showInputDialog(null, "加密后的字符串为", RsaUtils.encrypt(data));
						}
					}
					if (ke.getKeyCode() == KeyEvent.VK_I && ke.isControlDown() && ke.isShiftDown() && ke.getID() == KeyEvent.KEY_PRESSED) {
						try {
							Runtime.getRuntime().exec("cmd /c start notepad db.ini");
						} catch (Exception e) {
							e.printStackTrace();
							JOptionPane.showMessageDialog(null, e.getMessage());
						}
					}
				}
			}
		}, java.awt.AWTEvent.KEY_EVENT_MASK);
		label.setIcon(image);
		toolBar.addSeparator();
		toolBar.add(button1);
		toolBar.addSeparator();
		toolBar.add(label);
		toolBar.addSeparator();
		toolBar.add(button2);
		toolBar.addSeparator();
		toolBar.setFloatable(false);
		this.setIconImage(image.getImage());
		this.setTitle(APP_TITLE);
		this.add(toolBar, BorderLayout.NORTH);
		this.setUndecorated(true);
		this.pack();
		int width = toolkit.getScreenSize().width;
		this.setLocation((width - this.getSize().width) / 2, 0);
		this.setAlwaysOnTop(true);
		this.setVisible(true);
		button2.requestFocus();
	}

	public static void main(String[] args) {
		new MainFrame();
	}

	private static void dc() {
		Connection sconn = null;
		Connection aconn = null;
		count = 0;
		try {
			sconn = SQLServerDBManager.getConnection();
			aconn = AccessDBManager.getConnection();
			sconn.setAutoCommit(false);
			QueryRunner runner = new QueryRunner();
			try {
				long index = 0;
				List<Object> max = runner.query(sconn, SQLSERVER_QRLIST_SELECT, new ColumnListHandler<Object>());
				if (max.size() > 0 && max.get(0) != null) {
					index = Long.valueOf(max.get(0).toString());
				}
				CachedRowSet crs1 = AccessDBManager.query(aconn, String.format(ACCESS_QRLIST_SELECT, index));
				String uuid = null;
				while (crs1.next()) {
					if (crs1.getInt("Num") == 0) {
						count++;
						uuid = StringUtils.uuid();
					}
					runner.update(sconn, SQLSERVER_QRGROUP_INSERT, crs1.getString("SeqNo"), uuid);
					runner.update(sconn, SQLSERVER_QRLIST_INSERT, crs1.getString("SeqNo"), crs1.getInt("Num"), crs1.getString("AgName").trim(), crs1.getString("AnaDateTime"), crs1.getString("Kind").trim(), "0", "0");
				}
				CachedRowSet crs2 = AccessDBManager.query(aconn, String.format(ACCESS_QRDATA_SELECT, index));
				while (crs2.next()) {
					String content = crs2.getString("Content").trim();
					if (content.startsWith(".")) {
						content = "0" + content;
					}
					runner.update(sconn, SQLSERVER_QRDATA_INSERT, crs2.getString("SeqNo"), crs2.getInt("SubNo"), crs2.getString("DispEle").trim(), content);
				}
				sconn.commit();
			} catch (Exception e) {
				e.printStackTrace();
				sconn.rollback();
				throw new RuntimeException(e);
			}
			if (count > 0) {
				JOptionPane.showMessageDialog(null, String.format(MSG_DC, count));
			} else {
				JOptionPane.showMessageDialog(null, "未发现新数据");
			}
		} catch (Exception e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, e.getMessage());
		} finally {
			AccessDBManager.closeConnection(aconn);
			SQLServerDBManager.closeConnection(sconn);
		}
	}
}